import { _decorator, Component, EventTouch, Node, ProgressBarComponent, UITransform, v2, v3, Vec2 } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('joyStick')
export class joyStick extends Component {
  @property(Node) center: Node = null

  private limitR: number = 75 //摇杆背景的半径
  private UITran: UITransform = null
  private outV2: Vec2 = new Vec2(0, 0)

  protected onLoad(): void {
    this.init()
    this.node.on(Node.EventType.TOUCH_START, this.onTouchStart, this)
    this.node.on(Node.EventType.TOUCH_MOVE, this.onTouchMove, this)
    this.node.on(Node.EventType.TOUCH_END, this.onTouchEnd, this)
    this.node.on(Node.EventType.TOUCH_CANCEL, this.onTouchCancel, this)
  }

  update(deltaTime: number) {

  }

  getOutV2() {
    return this.outV2
  }

  init() {
    this.limitR = this.node.getComponent(UITransform).contentSize.width / 2
    this.UITran = this.node.getComponent(UITransform)
  }

  onTouchStart(event: EventTouch) {
    // let pos = event.getUILocation()
    // this.center.setWorldPosition(pos.x, pos.y, 0)
    let worldPos = event.getUILocation()
    // this.center.setWorldPosition(worldPos.x, worldPos.y, 0)
    let nodePos = this.UITran.convertToNodeSpaceAR(v3(worldPos.x, worldPos.y, 0))
    // let r = Math.sqrt(nodePos.x * nodePos.x + nodePos.y * nodePos.y)
    // console.log(nodePos.x, nodePos.y)
    let len = v2(nodePos.x, nodePos.y).length()
    let dir = v2(nodePos.x, nodePos.y).normalize()
    let scale = len > this.limitR ? this.limitR : len
    let out = dir.multiplyScalar(scale)
    this.center.setPosition(out.x, out.y, 0)
    this.outV2.set(out.x, out.y)
  }
  onTouchMove(event: EventTouch) {
    let worldPos = event.getUILocation()
    // this.center.setWorldPosition(worldPos.x, worldPos.y, 0)
    let nodePos = this.UITran.convertToNodeSpaceAR(v3(worldPos.x, worldPos.y, 0))
    // let r = Math.sqrt(nodePos.x * nodePos.x + nodePos.y * nodePos.y)
    // console.log(nodePos.x, nodePos.y)
    let len = v2(nodePos.x, nodePos.y).length()
    let dir = v2(nodePos.x, nodePos.y).normalize()
    let scale = len > this.limitR ? this.limitR : len
    let out = dir.multiplyScalar(scale)
    this.center.setPosition(out.x, out.y, 0)
    this.outV2.set(out.x, out.y)
  }
  onTouchEnd(event: EventTouch) {
    this.center.setPosition(0, 0, 0)
    this.outV2.set(0, 0)
  }
  onTouchCancel(event: EventTouch) {
    this.center.setPosition(0, 0, 0)
    this.outV2.set(0, 0)
  }
}


